package top.techqi.view.recyclerview

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView

/**
 * RecyclerView在表格布局中的间距控制
 * @param spaceH 网格元素之间的水平间距
 * @param spaceH 网格元素之间的垂直间距
 * @param left/top/right/bottom 网格贴边间距
 */
@Suppress("MemberVisibilityCanBePrivate")
open class TableItemDecoration private constructor(
    val spaceH: Int, val spaceV: Int,
    val left: Int, val top: Int,
    val right: Int, val bottom: Int
) : RecyclerView.ItemDecoration() {
    constructor(
        spaceH: Number, spaceV: Number = spaceH,
        left: Number = spaceH.toFloat() / 2,
        top: Number = spaceV.toFloat() / 2,
        right: Number = left, bottom: Number = top
    ) : this(
        spaceH.toInt(), spaceV.toInt(), left.toInt(), top.toInt(), right.toInt(), bottom.toInt()
    )

    override fun getItemOffsets(
        outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State
    ) {
        val lm = parent.layoutManager as? TableLayoutManager ?: return
        val position = parent.getChildAdapterPosition(view)

        val curCol = position % lm.colCount
        val curRow = position / lm.colCount

        val everyH = spaceH / 2
        val everyV = spaceV / 2

        if (curCol == 0) outRect.left = left
        else outRect.left = everyH
        if (curCol == lm.colCount - 1) outRect.right = right
        else outRect.right = everyH

        if (curRow == 0) outRect.top = top
        else outRect.top = everyV
        if (curRow == lm.rowCount - 1) outRect.bottom = bottom
        else outRect.bottom = everyV
    }
}